package com.ziytek.web.citizen.service;

import com.google.gson.Gson;
import com.ziytek.web.citizen.configuration.RefreshSqliteConfiguration;
import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.constant.ServerConstant;
import com.ziytek.web.citizen.constant.TableConstant;
import com.ziytek.web.citizen.enums.ResponseEnum;
import com.ziytek.web.citizen.mapper.HistoryTableMapper;
import com.ziytek.web.citizen.mapper.TableMapper;
import com.ziytek.web.citizen.model.req.CapDetailQueryReq;
import com.ziytek.web.citizen.model.rsp.CapDetailQueryRsp;
import com.ziytek.web.citizen.model.vo.CapDetailVo;
import com.ziytek.web.citizen.model.vo.RealTimeVo;
import com.ziytek.web.citizen.model.vo.StatsDo;
import com.ziytek.web.citizen.util.DateTimeUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 容量详情数据查询
 *
 * @author fenghx
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CapacityDetailService {
    private final Gson gson;
    private final TableMapper tableMapper;
    private final HistoryTableMapper historyTableMapper;
    private final CompressionService compressionService;
    private final RefreshSqliteConfiguration refreshSqliteConfiguration;

    public CapDetailQueryRsp capDetailQuery(CapDetailQueryReq req) {
        var rsp = new CapDetailQueryRsp();
        rsp.setRetErrorData("查询无数据");

        var cab = req.getCabinetNo();
        var batchNo = req.getBatchNo();
        var pagNum = req.getPageNum() == null ? NumConstant.INT_ONE : req.getPageNum();
        var pageSize = req.getPageSize() == null ? NumConstant.INT_TWO_TEN : req.getPageSize();

        batchNo = batchNo.replaceAll("-", "")
                .replaceAll(":", "")
                .replaceAll(" ", "");
        var count = tableMapper.queryStatsDoListCount(TableConstant.TABLE_REAL_TIME_STATS, Integer.parseInt(cab), batchNo);
        if (count <= NumConstant.INT_ZERO) {
            rsp.setRetErrorData("查询count为0");
            return rsp;
        }

        var offset = (pagNum - NumConstant.INT_ONE) * pageSize;
        var sdo = tableMapper.queryStatsDoList(TableConstant.TABLE_REAL_TIME_STATS, Integer.parseInt(cab), batchNo, offset, pageSize);
        if (CollectionUtils.isEmpty(sdo)) {
            return rsp;
        }

        //sdo.sort(Comparator.comparingInt(StatsDo::getCnn));
        for (var s : sdo) {
            rsp.setCapDetailVo(oneCapStatusDetailVo(s));
        }

        var rspPageNum = count / pageSize;
        if (count % pageSize != NumConstant.INT_ZERO) {
            rspPageNum++;
        }

        rsp.setRetSuccessData((int) rspPageNum, count.intValue());
        rsp.setRetCode(ServerConstant.SUCCESS);
        rsp.setRetMsg(ResponseEnum.SUCCESS.getDesc());
        return rsp;
    }

    public CapDetailQueryRsp historyCapDetailQuery(CapDetailQueryReq req) {
        var rsp = new CapDetailQueryRsp();
        rsp.setRetErrorData("查询无数据");

        var cab = req.getCabinetNo();
        var batchNo = req.getBatchNo();
        var pageSize = NumConstant.INT_FINISH;

        batchNo = batchNo.replaceAll("-", "")
                .replaceAll(":", "")
                .replaceAll(" ", "");

        // 先加载数据库，在切换数据库DB文件
        var dbName = "Data_" + batchNo.substring(NumConstant.INT_TWO, NumConstant.INT_EIGHT);
        refreshSqliteConfiguration.updateYmlData("historyDbName", dbName);

        var count = historyTableMapper.queryStatsDoListCount(TableConstant.TABLE_REAL_TIME_STATS, Integer.parseInt(cab), batchNo);
        if (count <= NumConstant.INT_ZERO) {
            rsp.setRetErrorData("查询count为0");
            return rsp;
        }

        var offset = NumConstant.INT_ZERO;
        var sdo = historyTableMapper.queryStatsDoList(TableConstant.TABLE_REAL_TIME_STATS, Integer.parseInt(cab), batchNo, offset, pageSize);
        if (CollectionUtils.isEmpty(sdo)) {
            return rsp;
        }

        for (var s : sdo) {
            rsp.setCapDetailVo(oneCapStatusDetailVo(s));
        }

        var rspPageNum = count / pageSize;
        if (count % pageSize != NumConstant.INT_ZERO) {
            rspPageNum++;
        }

        rsp.setRetSuccessData((int) rspPageNum, count.intValue());
        rsp.setRetCode(ServerConstant.SUCCESS);
        rsp.setRetMsg(ResponseEnum.SUCCESS.getDesc());
        return rsp;
    }

    private CapDetailVo oneCapStatusDetailVo(StatsDo sdo) {

        byte[] data;
        try {
            data = compressionService.decompress(sdo.getData());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        var v = gson.fromJson(new String(data, StandardCharsets.UTF_8), RealTimeVo.class);
        // 没数据
        if (v == null) {
            return null;
        }

        var vo = new CapDetailVo();
        vo.setSeq(String.valueOf(sdo.getId()));
        vo.setChannelNo(v.getCn() + "-" + v.getBn() + "-" + v.getCnn());
        vo.setBatteryNo(v.getCn() + "-" + v.getBn() + "-" + v.getCnn());
        vo.setExecutionTime(DateTimeUtils.toDate(sdo.getCreateTime()));
        var capStr = String.format("%.2f", v.getCpa());
        vo.setCapacity(capStr + "mAh");
        vo.setCurrent(v.getC() + "mA");
        vo.setVoltage(v.getV() + "mV");
        vo.setTemperature("0.0℃");
        vo.setState("良好");
        return vo;
    }
}
